<template>
  <view class="container">
    <view class="header">
      <text class="title">Excel文件下载</text>
    </view>
    
    <view class="content">
      <button class="download-btn" @click="downloadExcel" :loading="loading">
        {{ loading ? '下载中...' : '下载Excel文件' }}
      </button>
      
      <view class="progress-container" v-if="progress > 0">
        <text>下载进度: {{ progress }}%</text>
        <progress :percent="progress" show-info stroke-width="3" />
      </view>
      
      <view class="file-info" v-if="filePath">
        <text>文件已保存到: {{ filePath }}</text>
        <button class="open-btn" @click="openFile">打开文件</button>
      </view>
      
      <view class="error-message" v-if="error">
        <text class="error-text">{{ error }}</text>
      </view>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      loading: false,
      progress: 0,
      filePath: '',
      error: ''
    }
  },
  methods: {
    async downloadExcel() {
      this.loading = true
      this.progress = 0
      this.error = ''
      
      try {
        // 替换为你的Excel文件URL
        const fileUrl = 'https://example.com/path/to/your/file.xlsx'
        
        // 使用uni.downloadFile下载文件
        const downloadTask = uni.downloadFile({
          url: fileUrl,
          success: (res) => {
            if (res.statusCode === 200) {
              this.saveFile(res.tempFilePath)
            } else {
              this.error = `下载失败，状态码: ${res.statusCode}`
              this.loading = false
            }
          },
          fail: (err) => {
            console.error('下载失败:', err)
            this.error = '下载失败，请检查网络连接'
            this.loading = false
          }
        })
        
        // 监听下载进度
        downloadTask.onProgressUpdate((res) => {
          this.progress = res.progress
        })
        
      } catch (err) {
        console.error('下载出错:', err)
        this.error = '下载过程中发生错误'
        this.loading = false
      }
    },
    
    async saveFile(tempFilePath) {
      try {
        // 获取文件后缀名
        const fileExtension = tempFilePath.split('.').pop().toLowerCase()
        
        // 安卓保存文件到本地
        const savedFilePath = await new Promise((resolve, reject) => {
          plus.io.resolveLocalFileSystemURL(tempFilePath, (fileEntry) => {
            const fileName = `excel_${new Date().getTime()}.${fileExtension}`
            
            plus.io.resolveLocalFileSystemURL(plus.io.PUBLIC_DOWNLOADS, (dirEntry) => {
              dirEntry.getFile(fileName, { create: true }, (newFile) => {
                fileEntry.copyTo(dirEntry, fileName, () => {
                  resolve(newFile.fullPath)
                }, (err) => {
                  reject(err)
                })
              }, (err) => {
                reject(err)
              })
            }, (err) => {
              reject(err)
            })
          }, (err) => {
            reject(err)
          })
        })
        
        this.filePath = savedFilePath
        uni.showToast({
          title: '文件保存成功',
          icon: 'success'
        })
        
      } catch (err) {
        console.error('保存文件失败:', err)
        this.error = '保存文件失败'
      } finally {
        this.loading = false
      }
    },
    
    openFile() {
      if (!this.filePath) return
      
      plus.runtime.openFile(this.filePath, {
        error: (e) => {
          uni.showToast({
            title: '打开文件失败',
            icon: 'none'
          })
          console.error('打开文件失败:', e)
        }
      })
    }
  }
}
</script>

<style>
.container {
  padding: 20px;
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.header {
  margin-bottom: 30px;
}

.title {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.download-btn {
  width: 80%;
  background-color: #007AFF;
  color: white;
  border-radius: 8px;
  margin-bottom: 20px;
}

.progress-container {
  width: 80%;
  margin-bottom: 20px;
}

.file-info {
  width: 80%;
  margin-top: 20px;
  padding: 15px;
  background-color: #f5f5f5;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
}

.open-btn {
  width: 60%;
  margin-top: 10px;
  background-color: #4CD964;
  color: white;
  border-radius: 8px;
}

.error-message {
  width: 80%;
  margin-top: 20px;
  padding: 15px;
  background-color: #FFF2F0;
  border-radius: 8px;
}

.error-text {
  color: #FF4D4F;
  text-align: center;
}
</style>